/*

  xmunipack - main

  Copyright © 2009-2011 F.Hroch (hroch@physics.muni.cz)

  This file is part of Munipack.

  Munipack is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  Munipack is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with Munipack.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "xmunipack.h"
#include <wx/wx.h>
#include <wx/app.h>
#include <wx/cmdline.h>
#include <wx/debugrpt.h>
#include <wx/protocol/ftp.h>
#include <wx/wfstream.h>
#include <cstdlib>

#define FTP_LOGIN     "wxDebugReport"
#define FTP_PASSWORD  "wxDebugReport"
#define FTP_SERVER    "integral.physics.muni.cz"


wxIMPLEMENT_APP(XMunipack);

bool XMunipack::OnInit()
{
  config = 0;

  wxString file;

  wxLogDebug(INFOTEXT " " XVERSION " " COPYLEFT);


  // command line parameters

  wxCmdLineParser cmd(argc,argv);
  cmd.SetLogo(INFOTEXT " " XVERSION ", " COPYLEFT "\n" INFOTEXTFULL);

  cmd.AddSwitch(wxEmptyString,"version","print version and license");
  cmd.AddParam("filename",wxCMD_LINE_VAL_STRING,wxCMD_LINE_PARAM_OPTIONAL);

  OnInitCmdLine(cmd);

  switch (cmd.Parse()) {

  case 0:

    if (cmd.Found("version")) {
      wxPrintf("%s %s, %s\n%s\n",INFOTEXT,XVERSION,COPYLEFT,INFOTEXTFULL);
      wxPrintf("\n");
      wxPrintf("Munipack comes with ABSOLUTELY NO WARRANTY.\n");
      wxPrintf("You may redistribute copies of Munipack\n");
      wxPrintf("under the terms of the GNU General Public License.\n");
      wxPrintf("For more information about these matters, see the file named COPYING.\n");
      return false;
    }
    break;

  default:
    
    // cmd.Usage() is called by default
    return false;

  };


  if( cmd.GetParamCount() > 0 )
    file = cmd.GetParam();


  // initialisation

  wxHandleFatalExceptions();
  wxInitAllImageHandlers();  
  config = new MuniConfig();

#ifdef __WXMAC__
  // all main windows?
  SetExitOnFrameDelete(true);
  wxMenuBar *menubar = new wxMenuBar;
  wxMenuBar::MacSetCommonMenuBar(menubar);
#endif


// setup by environment of paths for binaries and libraries
  wxString xpath;
  wxGetEnv("PATH",&xpath);

#ifdef MUNIPACK_BIN_PATH
  xpath = wxString(MUNIPACK_BIN_PATH) + wxString(":") + xpath;
#endif

#ifdef MUNIPACK_LIBEXEC_PATH
  xpath = wxString(MUNIPACK_LIBEXEC_PATH) + wxString(":") + xpath;
#endif

  wxString libexecpath;
  if( wxGetEnv("MUNIPACK_LIBEXEC",&libexecpath) )
    xpath = libexecpath + wxString(":") + xpath;

  wxString binpath;
  if( wxGetEnv("MUNIPACK_BIN",&binpath) )
    xpath = binpath + wxString(":") + xpath;

  wxSetEnv("PATH",xpath.c_str());

  // obsoleted by static linking of drivers
#ifdef MUNIPACK_PLDRV_PATH
  if( ! wxGetEnv("PLPLOT_DRV_DIR",0) )
    wxSetEnv("PLPLOT_DRV_DIR",MUNIPACK_PLDRV_PATH);
#endif

  // required, colortables and helper files
#ifdef MUNIPACK_PLLIB_PATH
  if( ! wxGetEnv("PLPLOT_LIB",0) )
    wxSetEnv("PLPLOT_LIB",MUNIPACK_PLLIB_PATH);
#endif

  if( ! file.IsEmpty() ) {

    MuniView *view = new MuniView(NULL,config);
    view->Show();
    view->LoadFile(file);

    return true;
  }

  MuniBrowser *browser = new MuniBrowser(NULL,config);
  browser->Show(true);

  return true;
}


int XMunipack::OnExit()
{
  delete config;
  return 0;
}


void XMunipack::OnFatalException()
{
  wxDebugReport report;
  wxDebugReportPreviewStd preview;

  report.AddAll();

  if ( preview.Show(report) ) {

    // upload the report to home ftp
    for(size_t i = 0; i < report.GetFilesCount(); i++) {
      wxString name, desc;
      report.GetFile(i,&name,&desc);
      wxFileName file(report.GetDirectory(),name);

      wxFTP ftp;
      ftp.SetUser(FTP_LOGIN);
      ftp.SetPassword(FTP_PASSWORD);

      if ( !ftp.Connect(FTP_SERVER) ) {
        wxLogError("Couldn't send bug report: Failed to connect.\n" 
		   "Leaving files in "+report.GetDirectory()+".\n");
	report.Reset();
        return;
      }

      wxDateTime dt(wxDateTime::Now());
      dt.MakeUTC();
      wxString oname(dt.Format("%Y-%m-%d_%H:%M:%S_")+name);
      wxOutputStream *out = ftp.GetOutputStream(oname);
      wxFileInputStream in(file.GetFullPath());
      wxASSERT(in.IsOk() && out && out->IsOk());
      if( out ) {
	out->Write(in);
	delete out;
      }

    }

  }
}

